﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FreeDream.Common.Other
{
    public class ConvertHelper
    {
        /// <summary>
        /// Dictionary转Model类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mod"></param>
        /// <returns></returns>
        public static T ParseDictionaryToModel<T>(Dictionary<string, string> dict)
        {
            T obj = default(T);
            obj = Activator.CreateInstance<T>();

            //根据Key值设定 Columns
            foreach (KeyValuePair<string, string> item in dict)
            {
                System.Reflection.PropertyInfo prop = obj.GetType().GetProperty(item.Key);
                if (!string.IsNullOrEmpty(item.Value))
                {
                    object value = item.Value;
                    //Nullable 获取Model类字段的真实类型
                    Type itemType = Nullable.GetUnderlyingType(prop.PropertyType) == null ? prop.PropertyType : Nullable.GetUnderlyingType(prop.PropertyType);
                    //根据Model类字段的真实类型进行转换
                    prop.SetValue(obj, Convert.ChangeType(value, itemType), null);
                }


            }
            return obj;
        }

        /// <summary>
        /// obj添加一个属性
        /// </summary>
        /// <param name="obj">待添加属性的对象</param>
        /// <param name="key">键名</param>
        /// <param name="value">值</param>
        /// <returns>添加属性后的对象</returns>
        public static object Add(object obj, string key, object value)
        {
            JObject jObj = JObject.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(obj));
            jObj.Add(new JProperty(key, value));
            return Newtonsoft.Json.JsonConvert.DeserializeObject(jObj.ToString());
        }
        /// <summary>
        /// 字符数组转换成json字符串
        /// </summary>
        /// <param name="strs">{ "a", "b", "c", "d" }</param>
        /// <returns></returns>
        public static string ArrToJson(string[] strs)
        {
            JObject jo = new JObject();
            JObject parent = jo;

            foreach (var t in strs)
            {
                var jo2 = new JObject();
                parent[t] = jo2;
                parent = jo2;
            }
            return jo.ToString();
        }

    }
}
